package cn.itcast.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * gateway网关全局过滤
 *
 * @author yuanbailin
 * @since v1.0  2022-03-27 17:32
 */
//@Order(-1)    //拦截顺序，值越小排在最前面，当然负数是最小的
@Component  //声明为spring bean
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        //2.获取参数authorization参数
        String auth = params.getFirst("authorization");
        //3.判断请求参数是否等于admin
        if (StringUtils.equals(auth, "admin")) {
            //4.是，放行
            return chain.filter(exchange);
        } else {
            //5.否，拦截
            //5.1.设置状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //5.2.拦截请求
            return exchange.getResponse().setComplete();
        }
    }

    /**
     * 通过实现ordered接口也可以实现拦截器排序，同样值越小越先执行
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
